import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';
import * as docx from 'docx';
import SiteConfigService from './siteConfigService';
import { TrainerService } from './trainerService';
import { VTranRecordInfoService } from './vTranRecordInfoService';
import { DoctorService } from './doctorService';
import { DiseaseService } from './diseaseService';
import { CheckItemService } from './checkItemService';
import { Trainer } from '../../types/trainer';
import { VTranRecordInfo } from '../../types/vTranRecordInfo';
import { SiteConfig } from '../../types/siteConfig';
import { Doctor } from '../../types/doctor';
import { Disease } from '../../types/disease';
import { CheckItem } from '../../types/checkItem';

import { getBestChineseFont, preloadChineseFonts } from '../../utils/fonts';
import { invoke } from '@tauri-apps/api/core';
import { getFileStream } from '../index';
import { m_multiTranslateByDict } from '@/utils/toCase';

interface DownloadReportParams {
  trainer_id: number;
  course_date: string[];
  format?: 'pdf' | 'docx'; // 添加格式参数
}

interface ReportData {
  siteConfig: SiteConfig;
  trainer: Trainer;
  records: VTranRecordInfo[];
  chargeDoctor?: Doctor;
  trainDoctor?: Doctor;
  diseaseList: Disease[];
  checkItemList: CheckItem[];
}

export class DownloadService {
  /**
   * 生成评估报告PDF并下载
   */
  static async generateAssessmentReport(params: DownloadReportParams): Promise<Blob> {
    try {
      // 预加载中文字体
      await preloadChineseFonts();
      // 1. 获取基础配置信息
      const siteConfig = await SiteConfigService.getById(1);
      if (!siteConfig) {
        throw new Error('未找到基础配置信息');
      }
      // 2. 获取患者信息
      const trainer = await TrainerService.findById(params.trainer_id);
      if (!trainer) {
        throw new Error('未找到患者信息');
      }

      // 3. 获取医生信息
      let chargeDoctor: Doctor | undefined;
      let trainDoctor: Doctor | undefined;
      
      if (trainer.charge_doctor) {
        chargeDoctor = await DoctorService.getById(trainer.charge_doctor);
      }
      
      if (trainer.train_doctor) {
        trainDoctor = await DoctorService.getById(trainer.train_doctor);
      }
      // 4. 获取训练记录
      const allRecords: VTranRecordInfo[] = [];
      const records = await VTranRecordInfoService.getTrainerRecords(params.trainer_id, params.course_date);
      allRecords.push(...records);

      // 5. 获取疾病和检查项目字典数据
      const diseaseList = await DiseaseService.list();
      const checkItemList = await CheckItemService.list();

      const reportData = {
        siteConfig,
        trainer,
        records: allRecords,
        chargeDoctor,
        trainDoctor,
        diseaseList,
        checkItemList
      };

      // 5. 生成DOCX文档
      return await this.generateDOCX(reportData);
    } catch (error) {
      console.error('生成评估报告失败:', error);
      throw new Error(`生成评估报告失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  /**
   * 生成DOCX文档
   */
  static async generateDOCX(data: ReportData): Promise<Blob> {
    try {
      const {
        Paragraph,
        Table,
        TableRow,
        TableCell,
        WidthType,
        AlignmentType,
        TextRun,
        HeadingLevel,
        BorderStyle,
        ShadingType,
        VerticalAlign,
      } = docx;

      // 转换疾病ID为名称
      const diseaseIds = data.trainer.disease ? JSON.parse(data.trainer.disease) : [];
      const diseaseNames = m_multiTranslateByDict(
        diseaseIds.join(','),
        data.diseaseList,
        'id',
        'name'
      );

      // 转换检查项目ID为名称
      const checkItemIds = data.trainer.check_items ? JSON.parse(data.trainer.check_items) : [];
      const checkItemNames = m_multiTranslateByDict(
        checkItemIds.join(','),
        data.checkItemList,
        'id',
        'name'
      );

      const doc = new docx.Document({
        sections: [{
          properties: {},
          children: [
            // 报告标题
            new Paragraph({
              text: "训练报告",
              heading: HeadingLevel.HEADING_1,
              alignment: AlignmentType.CENTER,
              spacing: { after: 400 },
            }),

            // 基本信息标题 - 四号加粗，添加细线
            new Paragraph({
              children: [
                new TextRun({
                  text: "基本信息",
                  bold: true,
                  size: 28 // 四号字体大小
                })
              ],
              heading: HeadingLevel.HEADING_2,
              spacing: { after: 100 },
              border: {
                bottom: {
                  color: "auto",
                  space: 1,
                  style: BorderStyle.SINGLE,
                  size: 2
                }
              }
            }),

            // 基本信息表格 - 隐藏框线，移除颜色
            new Table({
              width: { size: 100, type: WidthType.PERCENTAGE },
              borders: {
                top: { style: BorderStyle.NONE },
                bottom: { style: BorderStyle.NONE },
                left: { style: BorderStyle.NONE },
                right: { style: BorderStyle.NONE },
                insideHorizontal: { style: BorderStyle.NONE },
                insideVertical: { style: BorderStyle.NONE },
              },
              rows: [
                // 第一行：姓名和性别
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: "姓名",
                            size: 24 // 小四字体大小
                          })
                        ],
                        alignment: AlignmentType.LEFT,
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 20, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: data.trainer.name || "",
                            size: 24 // 小四字体大小
                          })
                        ],
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 30, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        text: "性别",
                        alignment: AlignmentType.LEFT,
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 20, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        text: data.trainer.gender === 1 ? '男' : data.trainer.gender === 2 ? '女' : '',
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 30, type: WidthType.PERCENTAGE }
                    })
                  ]
                }),
                // 第二行：年龄和出生日期
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: "年龄",
                            size: 24 // 小四字体大小
                          })
                        ],
                        alignment: AlignmentType.LEFT,
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 20, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: data.trainer.age?.toString() || "",
                            size: 24 // 小四字体大小
                          })
                        ],
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 30, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: "出生日期",
                            size: 24 // 小四字体大小
                          })
                        ],
                        alignment: AlignmentType.LEFT,
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 20, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: data.trainer.birthday || "",
                            size: 24 // 小四字体大小
                          })
                        ],
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 30, type: WidthType.PERCENTAGE }
                    })
                  ]
                }),
                // 第三行：建档日期和家长
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: "建档日期",
                            size: 24 // 小四字体大小
                          })
                        ],
                        alignment: AlignmentType.LEFT,
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 20, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: data.trainer.create_time || "",
                            size: 24 // 小四字体大小
                          })
                        ],
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 30, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: "家长",
                            size: 24 // 小四字体大小
                          })
                        ],
                        alignment: AlignmentType.LEFT,
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 20, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: data.trainer.contact || "",
                            size: 24 // 小四字体大小
                          })
                        ],
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 30, type: WidthType.PERCENTAGE }
                    })
                  ]
                }),
                // 第四行：联系电话和家庭地址
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: "联系电话",
                            size: 24 // 小四字体大小
                          })
                        ],
                        alignment: AlignmentType.LEFT,
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 20, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: data.trainer.tel || "",
                            size: 24 // 小四字体大小
                          })
                        ],
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 30, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: "家庭地址",
                            size: 24 // 小四字体大小
                          })
                        ],
                        alignment: AlignmentType.LEFT,
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 20, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: data.trainer.address || "",
                            size: 24 // 小四字体大小
                          })
                        ],
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 30, type: WidthType.PERCENTAGE }
                    })
                  ]
                })
              ]
            }),

            new Paragraph({ text: "", spacing: { after: 200 } }),

            // 诊断疾病标题 - 四号加粗，添加细线
            new Paragraph({
              children: [
                new TextRun({
                  text: "诊断疾病",
                  bold: true,
                  size: 28 // 四号字体大小
                })
              ],
              heading: HeadingLevel.HEADING_2,
              spacing: { after: 100 },
              border: {
                bottom: {
                  color: "auto",
                  space: 1,
                  style: BorderStyle.SINGLE,
                  size: 2
                }
              }
            }),

            // 诊断疾病表格 - 隐藏框线，移除颜色
            new Table({
              width: { size: 100, type: WidthType.PERCENTAGE },
              borders: {
                top: { style: BorderStyle.NONE },
                bottom: { style: BorderStyle.NONE },
                left: { style: BorderStyle.NONE },
                right: { style: BorderStyle.NONE },
                insideHorizontal: { style: BorderStyle.NONE },
                insideVertical: { style: BorderStyle.NONE },
              },
              rows: [
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: "病史",
                            size: 24 // 小四字体大小
                          })
                        ],
                        alignment: AlignmentType.LEFT,
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 20, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: data.trainer.medical_history || "",
                            size: 24 // 小四字体大小
                          })
                        ],
                        spacing: { line: 360 } // 1.5倍行距
                      })]
                    })
                  ]
                }),
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: "诊断疾病",
                            size: 24 // 小四字体大小
                          })
                        ],
                        alignment: AlignmentType.LEFT,
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 20, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        children: [
                          new TextRun({
                            text: diseaseNames || "",
                            size: 24 // 小四字体大小
                          })
                        ],
                        spacing: { line: 360 } // 1.5倍行距
                      })]
                    })
                  ]
                })
              ]
            }),
            

            new Paragraph({ text: "", spacing: { after: 200 } }),

            // 常规检查信息标题 - 四号加粗，添加细线
            new Paragraph({
              children: [
                new TextRun({
                  text: "常规检查信息",
                  bold: true,
                  size: 28 // 四号字体大小
                })
              ],
              heading: HeadingLevel.HEADING_2,
              spacing: { after: 100 },
              border: {
                bottom: {
                  color: "auto",
                  space: 1,
                  style: BorderStyle.SINGLE,
                  size: 2
                }
              }
            }),

            // 常规检查信息表格 - 隐藏框线，移除颜色
            new Table({
              width: { size: 100, type: WidthType.PERCENTAGE },
              borders: {
                top: { style: BorderStyle.NONE },
                bottom: { style: BorderStyle.NONE },
                left: { style: BorderStyle.NONE },
                right: { style: BorderStyle.NONE },
                insideHorizontal: { style: BorderStyle.NONE },
                insideVertical: { style: BorderStyle.NONE },
              },
              rows: [
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({
                        text: "检查项目",
                        alignment: AlignmentType.LEFT,
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 20, type: WidthType.PERCENTAGE }
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        text: checkItemNames || "",
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      width: { size: 80, type: WidthType.PERCENTAGE }
                    })
                  ]
                }),
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({
                        text: "检查情况",
                        alignment: AlignmentType.LEFT,
                        spacing: { line: 360 } // 1.5倍行距
                      })]
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        text: data.trainer.check_result || "",
                        spacing: { line: 360 } // 1.5倍行距
                      })]
                    })
                  ]
                })
              ]
            }),

            new Paragraph({ text: "", spacing: { after: 200 } }),

            // 训练记录标题 - 四号加粗，添加细线
            new Paragraph({
              children: [
                new TextRun({
                  text: "训练记录",
                  bold: true,
                  size: 28 // 四号字体大小
                })
              ],
              heading: HeadingLevel.HEADING_2,
              spacing: { after: 100 },
              border: {
                bottom: {
                  color: "auto",
                  space: 1,
                  style: BorderStyle.SINGLE,
                  size: 2
                }
              }
            }),

            // 训练记录表格
            new Table({
              width: { size: 100, type: WidthType.PERCENTAGE },
              borders: {
                top: { style: BorderStyle.SINGLE },
                bottom: { style: BorderStyle.SINGLE },
                left: { style: BorderStyle.SINGLE },
                right: { style: BorderStyle.SINGLE },
                insideHorizontal: { style: BorderStyle.SINGLE },
                insideVertical: { style: BorderStyle.SINGLE },
              },
              rows: [
                // 表头
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({
                        text: "训练日期",
                        alignment: AlignmentType.CENTER,
                        // spacing: { line: 360 } // 1.5倍行距
                      })],
                      shading: {
                        color: 'cdcdcd',
                        type: ShadingType.SOLID, // 必须指定填充类型
                      },
                      verticalAlign: VerticalAlign.CENTER
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        text: "训练场次",
                        alignment: AlignmentType.CENTER,
                        // spacing: { line: 360 } // 1.5倍行距
                      })],
                      shading: {
                        color: 'cdcdcd',
                        type: ShadingType.SOLID, // 必须指定填充类型
                      },
                      verticalAlign: VerticalAlign.CENTER
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        text: "训练时间",
                        alignment: AlignmentType.CENTER,
                        // spacing: { line: 360 } // 1.5倍行距
                      })],
                      shading: {
                        color: 'cdcdcd',
                        type: ShadingType.SOLID, // 必须指定填充类型
                      },
                      verticalAlign: VerticalAlign.CENTER
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        text: "训练场景",
                        alignment: AlignmentType.CENTER,
                        // spacing: { line: 360 } // 1.5倍行距
                      })],
                      shading: {
                        color: 'cdcdcd',
                        type: ShadingType.SOLID, // 必须指定填充类型
                      },
                      verticalAlign: VerticalAlign.CENTER
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        text: "康复师",
                        alignment: AlignmentType.CENTER,
                        // spacing: { line: 360 } // 1.5倍行距
                      })],
                      shading: {
                        color: 'cdcdcd',
                        type: ShadingType.SOLID, // 必须指定填充类型
                      },
                      verticalAlign: VerticalAlign.CENTER
                    })
                  ]
                }),
                // 数据行
                ...data.records.map(record => new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({
                        text: record.course_date || "",
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      verticalAlign: VerticalAlign.CENTER
                    }),
                    
                   /**new TableCell({
                      children: [new Paragraph({
                        text: record.train_doctor ? data.trainDoctor?.name || "" : "",
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      verticalAlign: AlignmentType.CENTER
                    }), */ 
                    new TableCell({
                      children: [new Paragraph({
                        text: record.course_time_name || "",
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      verticalAlign: VerticalAlign.CENTER
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        text: `${record.start_time || ""}-${record.end_time || ""}`,
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      verticalAlign: VerticalAlign.CENTER
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        text: record.scens_name || "",
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      verticalAlign: VerticalAlign.CENTER
                    }),
                    new TableCell({
                      children: [new Paragraph({
                        text: record.train_doctor ? data.trainDoctor?.name || "" : "",
                        spacing: { line: 360 } // 1.5倍行距
                      })],
                      verticalAlign: VerticalAlign.CENTER
                    })
                  ]
                }))
              ]
            }),

            new Paragraph({ text: "", spacing: { after: 400 } }),

            // 责任医生签字
            new Paragraph({
              children: [
                new TextRun({ text: "责任医生：___________________", bold: true })
              ],
              alignment: AlignmentType.RIGHT
            }),

            new Paragraph({ text: "", spacing: { after: 200 } }),

            // 报告日期
            new Paragraph({
              children: [
                // 报告日期 yyyy年MM月dd日
                new TextRun({ text: `报告日期： ${new Date().getFullYear()}年${new Date().getMonth() + 1}月${new Date().getDate()}日`, bold: true })
              ],
              alignment: AlignmentType.RIGHT
            })
          ]
        }]
      });

      // 生成Blob - 使用浏览器兼容的方法
      const blob = await docx.Packer.toBlob(doc);
      return blob;
      
    } catch (error) {
      console.error('生成DOCX文档失败:', error);
      throw new Error(`生成DOCX文档失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  /**
   * 使用对话框下载文件
   */
  static async downloadWithDialog(blob: Blob, defaultFilename: string): Promise<string> {
    // 将Blob转换为Uint8Array
    const arrayBuffer = await blob.arrayBuffer();
    const fileData = Array.from(new Uint8Array(arrayBuffer));
    
    // 调用后端保存文件
    return await invoke('save_file_with_dialog', {
      fileData,
      defaultFilename
    });
  }
}